﻿using Gnivc.CarDealership.Api.Application.Abstractions.Repositories;
using Gnivc.CarDealership.Api.Domain.Entities;
using Microsoft.AspNetCore.Mvc;

namespace Gnivc.CarDealership.Api.Controllers;

[Route("api/[controller]")]
public class BrandsController : ApiController
{
    private readonly IBrandRepository _brandRepository;

    public BrandsController(IBrandRepository brandRepository)
    {
        _brandRepository = brandRepository;
    }

    [HttpGet("all")]
    public async Task<IResult> GetBrands()
    {
        var getBrandsResult = await _brandRepository.GetAllAsync();

        if(getBrandsResult.IsError)
            return Problem(getBrandsResult.Errors);

        var brands = getBrandsResult.Value;

        return Results.Ok(brands.Select(x => new 
        { 
            BrandId = x.Id, 
            BrandText = x.Name 
        }));
    }

    [HttpPost("create")]
    public async Task<IResult> CreateBrand([FromQuery] string name)
    {
        var brand = new Brand(Guid.NewGuid(), name);

        var addResult = await _brandRepository.AddAsync(brand);

        if (addResult.IsError)
            return Problem(addResult.Errors);

        return Results.Ok(new
        {
            BrandId = brand.Id,
            BrandText = brand.Name
        });
    }

    [HttpPatch("update")]
    public async Task<IResult> UpdateBrand(
        [FromQuery] Guid brandId, 
        [FromQuery] string name)
    {
        var getBrandResult = await _brandRepository.GetByIdAsync(brandId);

        if(getBrandResult.IsError)
            return Problem(getBrandResult.Errors);

        var brand = getBrandResult.Value!;

        brand.Name = name;

        var updateResult = await _brandRepository.UpdateAsync(brand);

        if(updateResult.IsError)
            return Problem(updateResult.Errors);

        return Results.Ok();
    }

    [HttpDelete("delete")]
    public async Task<IResult> DeleteBrand([FromQuery] Guid brandId)
    {
        var deleteResult = await _brandRepository.DeleteAsync(brandId);

        if (deleteResult.IsError)
            return Problem(deleteResult.Errors);

        return Results.Ok();
    }
}
